package qjc.m_堆;

import static com.排序.排序基础.选择排序.swap;

public class m1_数组中的第K个最大元素 {
    public int findKthLargest(int[] nums, int k) {
        int n = nums.length;
        int target = n - k;
        return quickSelect(nums, 0, n - 1, target);
    }

    private int quickSelect(int[] nums, int left, int right, int target) {
        int p = partition(nums, left, right);
        if (p == target) {
            return nums[p];
        } else if (p > target) {
            return quickSelect(nums, left, p - 1, target);
        } else {
            return quickSelect(nums, p + 1, right, target);
        }
    }

    private int partition(int[] nums, int left, int right) {
        int i = left, j = right;
        int pv = nums[left];
        while (i < j) {
            while (i < j && nums[j] > pv) {
                j--;
            }
            while (i<j && nums[i] < pv) {
                i++;
            }
            swap(nums,i,j);
        }
        swap(nums,left,j);
        return j;
    }
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
